package com.hyh.shiro.web;

import com.hyh.shiro.common.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Summerday
 */
@Slf4j
@RestController
public class LoginController {

    @GetMapping(value = "/hello")
    public AjaxResult hello() {
        return AjaxResult.ok("不用登陆,直接访问");
    }

    @GetMapping(value = "/index")
    public AjaxResult index() {
        return AjaxResult.ok("登录成功");
    }

    @GetMapping(value = "/denied")
    public AjaxResult denied() {
        return AjaxResult.error("权限不足");
    }

    @GetMapping("/login")
    public AjaxResult login(String username, String password) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            log.error("对用户[{}]进行登录验证,验证未通过,用户不存在", username);
            token.clear();
            return AjaxResult.error(e.getMessage());
        } catch (LockedAccountException e) {
            log.error("对用户[{}]进行登录验证,验证未通过,账户已锁定", username);
            token.clear();
            return AjaxResult.error(e.getMessage());
        } catch (ExcessiveAttemptsException e) {
            log.error("对用户[{}]进行登录验证,验证未通过,错误次数过多", username);
            token.clear();
            return AjaxResult.error(e.getMessage());
        } catch (AuthenticationException e) {
            log.error("对用户[{}]进行登录验证,验证未通过,堆栈轨迹如下", username, e);
            token.clear();
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.ok("登录成功");
    }
}
